<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 新增部门选择框 -->
      <el-form-item label="部门" prop="deptName" style="width: 210px;">
        <el-tree-select
          v-model="queryParams.deptName"
          :data="deptOptions"
          :props="{ value: 'deptName', label: 'deptName', children: 'children' }"
          node-key="deptId"
          placeholder="请选择部门"
          clearable
          filterable
          check-strictly
          default-expand-all
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="nickName" style="width: 220px;">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="领取时间" prop="claimTime">
        <el-input
          v-model="queryParams.claimTime"
          placeholder="请输入领取时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
     <!-- <el-form-item label="取餐码" prop="pickupNum" style="width: 200px;">
        <el-input
          v-model="queryParams.pickupNum"
          placeholder="请输入取餐码"
          clearable
          @keyup.enter="handleQuery"
      </el-form-item>-->
      <el-form-item label="取餐时间" prop="claimTime" style="width: 220px;">
        <el-date-picker clearable
          v-model="queryParams.claimTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择取餐时间">
        </el-date-picker>
      </el-form-item>
       <el-form-item label="订单状态" prop="status" style="width: 210px;">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="待取餐" value="0" />
          <el-option label="已取餐" value="1" />
          <el-option label="已取消" value="2" />
        </el-select>
      </el-form-item>
       <!-- 新增售卖类型下拉选择框 -->
       <!--<el-form-item label="售卖类型" prop="typeId" style="width: 210px;">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择售卖类型"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in saleTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Check"
          :disabled="multiple"
          @click="handleBatchVerification"
          v-hasPermi="['system:order:edit']"
        >批量核销</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
       <!-- 修改 selection 列，添加 selectable 属性 -->
      <el-table-column type="selection" width="55" align="center" :selectable="isSelectable" />
      
      <el-table-column label="订单号" align="center" prop="orderId" />
      <!-- <el-table-column label="用户id" align="center" prop="memberId" /> -->
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="所在部门" align="center" prop="deptName"  width="180"/>
      <el-table-column label="用户电话" align="center" prop="phonenumber" width="110"/>
      <el-table-column label="详细菜品" align="center" prop="productName" width="180"/>
      <el-table-column label="总数量" align="center" prop="quantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
        <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待取餐</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已取餐</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info">已取消</el-tag>
          <el-tag v-else type="danger">未知状态</el-tag>
        </template>
      </el-table-column>
     <el-table-column label="取餐码" align="center" prop="pickupNum">
        <template #default="scope">
          <span v-if="scope.row.pickupNum === '0' || scope.row.pickupNum === 0">已取餐</span>
          <span v-else>{{ scope.row.pickupNum }}</span>
        </template>
      </el-table-column>
       <el-table-column label="领取时间段" align="center" prop="claimTime" width="100"/>
      <!-- 修改核销时间列 -->
      <el-table-column label="核销时间" align="center" prop="pickupTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.pickupTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      
      <!-- 修改创建时间列 -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
            <el-button 
        v-if="scope.row.status === 0"
        type="primary" 
        icon="Check" 
        @click="handleVerification(scope.row)" 
        v-hasPermi="['system:order:edit']"
        size="small"
      >
        核销
      </el-button>
      
      <el-button 
        v-else-if="scope.row.status === 1"
        type="success" 
        icon="CircleCheck"
        disabled
        size="small"
      >
        已取餐
      </el-button>
      
      <el-button 
        v-else-if="scope.row.status === 2"
        type="info" 
        icon="CircleClose"
        disabled
        size="small"
      >
        已取消
      </el-button>
      
      <el-button 
        v-else
        type="warning" 
        disabled
        size="small"
      >
        未知状态
      </el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:order:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改卤味订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="领取时间" prop="claimTime">
          <el-input v-model="form.claimTime" placeholder="请输入领取时间" />
        </el-form-item>
        <el-form-item label="取餐码" prop="pickupNum">
          <el-input v-model="form.pickupNum" placeholder="请输入取餐码" />
        </el-form-item>
        <el-form-item label="核销时间" prop="pickupTime">
          <el-date-picker clearable
            v-model="form.pickupTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择核销时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入总数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, orderVerification, batchVerification } from "@/api/system/order"
import { listDept } from "@/api/system/dept" // 引入部门API
import { listSaleType } from "@/api/system/saleType" // 引入售卖类型API
const { proxy } = getCurrentInstance()

const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const deptOptions = ref([]) 
const saleTypeOptions = ref([]) //售卖类型选项


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: null,
    status: null,
    claimTime: null,
    pickupNum: null,
    pickupTime: null,
    deptName: null // 添加部门ID查询参数
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 将扁平的部门数据转换为树形结构
function convertToTree(flatData, parentId = 0) {
  const tree = []
  flatData.forEach(item => {
    if (item.parentId === parentId) {
      const children = convertToTree(flatData, item.deptId)
      if (children.length) {
        item.children = children
      }
      tree.push(item)
    }
  })
  return tree
}

// 获取部门树形数据
function getDeptTree() {
  listDept().then(response => {
    // 将扁平数据转换为树形结构
    deptOptions.value = convertToTree(response.data)
  })
}

// 获取售卖类型数据
function getSaleTypeList() {
  listSaleType().then(response => {
    saleTypeOptions.value = response.rows || response.data
  })
}

// 添加判断是否可选择的函数
function isSelectable(row, index) {
  // 只允许选择状态为0（待取餐）的订单
  return row.status === 0;
}
/**
 * 核销按钮操作
 */
function handleVerification(row) {
  proxy.$modal.confirm('是否确认核销订单编号为"' + row.orderId + '"的订单？').then(function() {
    // 调用核销接口，传递订单ID
    return orderVerification(row.orderId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("核销成功")
  }).catch(() => {})
}
/**
 * 批量核销按钮操作
 */
function handleBatchVerification() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一条订单记录");
    return;
  }
  
  proxy.$modal.confirm('是否确认核销选中的' + ids.value.length + '条订单？').then(function() {
    // 调用批量核销接口
    console.log(ids.value);
    return batchVerification(ids.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("批量核销成功");
    // 清空选择
    ids.value = [];
  }).catch(() => {
    proxy.$modal.msgError("批量核销失败");
  });
}
/** 查询卤味订单列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    memberId: null,
    status: null,
    totalAmount: null,
    claimTime: null,
    pickupNum: null,
    pickupTime: null,
    createTime: null,
    quantity: null,
    nickname: null,
    deptName: null // 添加部门ID重置
  }
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加卤味订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改卤味订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除卤味订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `订单列表_${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${new Date().getDate().toString().padStart(2, '0')}.xlsx`)
}
// 在组件初始化时获取部门数据
getSaleTypeList()
getDeptTree()
getList()
</script>
